import 'package:dio/src/dio.dart';
import 'package:flutter_learn/app/app_context.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../router/base_router_urls.dart';
import '../router/handlers/base_handler_list.dart';
import '../router/handlers/router_handler.dart';
import '../router/init_router.dart';
import '../router/model/home_handler_list.dart';
import '../router/router_observer.dart';

class MyAppContext extends AppContext{
  MyAppContext._internal();

  factory MyAppContext.of() {
    return MyAppContext._internal();
  }

  @override
  Future<void> onInit() async{
    await initRouter();
    print('初始化完成打印');
  }

  @override
  Future<Dio> onInitApiClient() {
    throw UnimplementedError();
  }

  @override
  Future<SharedPreferences> onInitSharedPreference() {
    return SharedPreferences.getInstance();
  }

  @override
  AppContext onNewInstance() {
    return this;
  }

  /// 初始化路由
  Future<void> initRouter() async {
    List<BaseHandlerList> handlers = [
      HomeHandlerList()
    ];

    // handlers.add(VolvoDemoRouterHandler());

    List<Handler> routerHandlers = [];
    for (final h in handlers) {
      routerHandlers.addAll(h.exportHandlerList());
    }

    /// import the routerHandlers registered in ModuleContext
    routerHandlers.addAll(this.routerHandlers);

    await InitRouter.instance.handle(routerHandlers, initialLocation: BaseRoutersUrls.home, observers: [routerObserver]);
  }

  Iterable<Handler> get routerHandlers {
    List<Handler> routerHandlers = [];
    for (final module in modules) {
      routerHandlers.addAll(module.routerHandlers);
    }

    return routerHandlers;
  }
}